﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Century.EnterpriseLibrary.Caching;
using log4net;
using Century.Model;
using System.Threading;

namespace Century.EnterpriseLibrary.Globalization.DbProvider
{
    internal static class PersistData
    {
        private static ILog Log
        {
            get
            {
                return Century.EnterpriseLibrary.LogHandler.Loging.LogWithName("Globalization");
            }
        }

        internal static string CurrentSite
        {
            get
            {
                return Thread.CurrentThread.CurrentUICulture.Name;
                //if (System.Web.HttpContext.Current.Session["CurrentSiteId"] == null)
                //{
                //    return "en-US";
                //}
                //return System.Web.HttpContext.Current.Session["CurrentSiteId"].ToString();
            }
        }

        #region [ Translation Texts ]

        /// <summary>
        /// Tranlation texts of the current site
        /// </summary>
        internal static CacheableList<TranslationText> SiteLabels
        {
            get
            {
                CacheableList<TranslationText> lst = CacheService.Instance.Get<CacheableList<TranslationText>>("TranslationText_" + CurrentSite, GetSiteLabels, new TimeSpan(0, 30, 0));

                //lst.OnAdd += new CacheableList<TranslationText>.CacheableListActionHandler(TranslationTextOnAdd);
                //lst.OnRemove += new CacheableList<TranslationText>.CacheableListActionHandler(TranslationTextOnRemove);
                //lst.OnUpdate += new CacheableList<TranslationText>.CacheableListActionHandler(TranslationTextOnUpdate);

                return lst;

            }
        }

        /// <summary>
        /// Get Site labels from db
        /// </summary>
        /// <returns></returns>
        internal static CacheableList<TranslationText> GetSiteLabels()
        {
            CacheableList<TranslationText> lst = new CacheableList<TranslationText>();
            using (CenturyDbContext db = new CenturyDbContext())
            {
                lst.AddRange(db.TranslationTexts.Where(c => c.Site == CurrentSite));
            }
            return lst;
        }


        //private static void TranslationTextOnAdd(CacheableList<TranslationText> list, TranslationText item, bool changeOnDb)
        //{
        //    if (changeOnDb)
        //    {
        //        using (CenturyDbContext db = new CenturyDbContext())
        //        {
        //            try
        //            {
        //                db.TranslationTexts.Add(item);
        //                db.SaveChanges();
        //            }
        //            catch (Exception exc)
        //            {
        //                Log.Error("Error on insert translation text", exc);
        //            }

        //        }
        //    }
        //}

        //private static void TranslationTextOnRemove(CacheableList<TranslationText> list, TranslationText item, bool changeOnDb)
        //{
        //    if (changeOnDb)
        //    {
        //        using (CenturyDbContext db = new CenturyDbContext())
        //        {
        //            try
        //            {
        //                db.TranslationTexts.Attach(item);
        //                db.TranslationTexts.Remove(item);
        //                db.SaveChanges();
        //            }
        //            catch (Exception exc)
        //            {
        //                Log.Error("Error on delete translation text", exc);
        //            }
        //        }
        //    }
        //}

        private static void TranslationTextOnUpdate(CacheableList<TranslationText> list, TranslationText item, bool changeOnDb)
        {
            if (changeOnDb)
            {
                using (CenturyDbContext db = new CenturyDbContext())
                {
                    try
                    {
                        TranslationText text = db.TranslationTexts.FirstOrDefault(t => t.Id == item.Id && t.Site == CurrentSite);
                        text.TranslationValue = item.TranslationValue;
                        db.SaveChanges();
                    }
                    catch (Exception exc)
                    {
                        Log.Error("Error on update translation text", exc);
                    }
                }
            }
        }

        #endregion


        #region [ Char Value ]


        public static CacheableList<CharValue> AllCharValues
        {
            get
            {
                CacheableList<CharValue> lst = null;
                //bool cacheData = true;// (System.Configuration.ConfigurationManager.AppSettings["CacheData"] == "true");

                lst = CacheManager.Get<CharValue>("CharValue");

                if (lst == null)
                {
                    lst = new CacheableList<CharValue>();
                    using (CenturyDbContext db = new CenturyDbContext())
                    {
                        lst.AddRange(db.CharValues.Include("CharValueTranslations").Include("CharType"));
                    }
                    lst.OnAdd += new CacheableList<CharValue>.CacheableListActionHandler(CharValueOnAdd);
                    lst.OnRemove += new CacheableList<CharValue>.CacheableListActionHandler(CharValueOnRemove);
                    lst.OnUpdate += new CacheableList<CharValue>.CacheableListActionHandler(CharValueOnUpdate);

                    CacheManager.Set<CharValue>("CharValue", lst);

                }
                return lst;

            }
        }


        private static void CharValueOnAdd(CacheableList<CharValue> list, CharValue item, bool changeOnDb)
        {
            if (changeOnDb)
            {
                using (CenturyDbContext db = new CenturyDbContext())
                {
                    try
                    {
                        db.CharValues.Add(item);
                        db.SaveChanges();
                    }
                    catch (Exception exc)
                    {
                        Log.Error("Error on insert Char Value", exc);
                    }
                }
            }
        }

        private static void CharValueOnRemove(CacheableList<CharValue> list, CharValue item, bool changeOnDb)
        {
            if (changeOnDb)
            {

                using (CenturyDbContext db = new CenturyDbContext())
                {
                    try
                    {
                        db.CharValues.Attach(item);
                        db.CharValues.Remove(item);
                        db.SaveChanges();
                    }
                    catch (Exception exc)
                    {
                        Log.Error("Error on delete Char Value", exc);
                    }
                }
            }
        }

        private static void CharValueOnUpdate(CacheableList<CharValue> list, CharValue item, bool changeOnDb)
        {
            if (changeOnDb)
            {

                using (CenturyDbContext db = new CenturyDbContext())
                {
                    try
                    {
                        // CharValue charValue = db.CharValues.FirstOrDefault(t => t.Id == item.Id);
                        //charValue. = item.TranslationValue;

                        db.CharValues.Attach(item);
                        db.SaveChanges();
                    }
                    catch (Exception exc)
                    {
                        Log.Error("Error on update Char Value", exc);
                    }
                }
            }
        }

        #endregion

        public static void AddCharTranlation(CharValueTranslation newTrans)
        {
            using (CenturyDbContext db = new CenturyDbContext())
            {
                try
                {
                    db.CharValueTranslations.Add(newTrans);
                    db.SaveChanges();
                }
                catch (Exception exc)
                {
                    Log.Error("Error on Add Char Tranlation", exc);
                }
            }


            CharValue charValue = AllCharValues.First(c => c.Id == newTrans.CharValueId);
            charValue.CharValueTranslations.Add(newTrans);
        }



    }
}
